﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AffordoPlugin.Model;
using BarcodeLib;

namespace AffordoPlugin.Print
{
	public class BarcodeUtil
	{
		public string GetBarCode(Message<BarcodeContent> message)
		{
			using (var barcode = new Barcode()
			{
				IncludeLabel = message.content.displayText,
				LabelFont = new Font("Arial", 12f),
				Alignment = AlignmentPositions.CENTER,
				BackColor = Color.White,
				ForeColor = Color.Black,
				Width = message.content.width,
				Height = message.content.height,
				ImageFormat = ImageFormat.Jpeg,
				StandardizeLabel = true
			})
			{
				var img = barcode.Encode(TYPE.CODE128, message.content.body);

				var ms = new MemoryStream();
				img.Save(ms, ImageFormat.Jpeg);

				var bytes = GetBytes(ms);

				return "data:image/png;base64,"+ Convert.ToBase64String(bytes);
			}
		}

		private byte[] GetBytes(Stream stream)
		{
			byte[] bytes = new byte[stream.Length];
			stream.Seek(0, SeekOrigin.Begin);
			stream.Read(bytes, 0, bytes.Length);
			
			return bytes;
		}
	}
}
